import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ZhongJinTao
 * Date: 2024-03-14
 * Time: 8:34
 */
public class TchEchoClient {
    Socket socket = null;

    public TchEchoClient(String serverIp, int serverPort) throws IOException {
        //这里的ip和port是直接发给socket的对象
        // 因为TCP是有连接的，所以socket会保存ip和port这些信息
        //因此TcpEchoClient不必保存ip和port
        socket = new Socket(serverIp, serverPort);
    }

    public void start() {
        System.out.println("客户端启动");

        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            Scanner scannerConsole = new Scanner(System.in);
            Scanner scannerNetwork = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream)) {
            while (true) {
                System.out.print("->");
                //1、从控制台输入请求，构造请求
                if(!scannerConsole.hasNext()) {
                    break;
                }
                //发送给服务器的字符串要带有 "\n"
                String request = scannerConsole.next();
                //2、把请求发给发送给服务器，这里需要用println来发生，确保信息里面有 "\n"
                //这里是和服务器的scanner.next()对应的
                writer.println(request);
                //通过flush刷新缓冲器，确保数据真的发出去了
                writer.flush();
                //3、接收服务器返回的响应
                //这里也是和服务器返回的响应逻辑对应，返回的响应带有 "\n"
                String response = scannerNetwork.next();
                //4、把返回的响应显示到控制台
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) throws IOException {
        TchEchoClient tchEchoClient = new TchEchoClient("127.0.0.1", 9090);
        tchEchoClient.start();
    }
}
